require(
		[ 'jquery', 'global', 'bootbox.min', 'module/util',
				'module/datatables', 'permission', 'module/popup',
				'module/ajax', 'jquery.validate', 'pixeladmin',
				'jquery.pnotify', 'requirejs/domready!' ],
		function($, global, bootbox, util, datatables, permission, popup) {
		window.PixelAdmin.start();
		jQuery.validator.addMethod("nameCheck", function(value, element) {
			return this.optional(element) || /[\u4E00-\u9FA5]/g.test(value);
		}, "只能是中文字");
		jQuery.validator.addMethod("mobileCheck", function(value, element) {
			return this.optional(element) || /^1[34578]\d{9}$/g.test(value);
		}, "手机号验证");
		var jobTable = null;
		var checkTr = function(data,type,full){
	    	return '<input type="checkbox" name="subBox" id="subBoxx" value="'+full.jobId+'"/>';
	    };
		var operate = function(data, type, full) {
			var str = "";
			var status = "";
			if(full.jobStatus=="0"){
				status = "";
			}else if(full.jobStatus=="1"){
				status = "暂停";
			}else{
				status = "恢复";
			}
			//if(permission.timedTaskedit){
				str += '<a data-toggle="modal" class="editJob" data-id="'
					+ full.jobId + '">编辑</a>&nbsp;';
			//}
			//if(permission.timedTaskstart){
				str += '<a data-toggle="modal" class="changeJobStatus" data-id="'
					+ full.jobId +','+full.jobStatus+ '">'+
					(full.jobStatus=='0'?'开始':'结束')
					+'</a>&nbsp;'; 
				str += '<a data-toggle="modal" class="PauseJob" data-id="'
					+ full.jobId + '">'+
					status
					+'</a>&nbsp;';
				str += '<a data-toggle="modal" class="ExeJob" data-id="'
					+ full.jobId + '">'+
					(full.jobStatus=='2'?'执行一次':'')
					+'</a>&nbsp;';
			//}
			//if(permission.timedTaskdelete){
				str += '<a data-toggle="modal" class="deleteJob" data-id="'
					+ full.jobId + '">'+"删除"
					+'</a>&nbsp;';
			//}
			return str;
		};
		var jobStatus = function(data, type, full){
			var str = "";
			if(full.jobStatus=="0"){
				str = "未启动";
			}else if(full.jobStatus=="1"){
				str = "执行";
			}else if(full.jobStatus=="2"){
				str = "暂停";
			}
			return str;
		};
		var _jobTable = function(){
			var options = {};
			options.tableId = '#jobTable';
			options.aaSorting = [[2,"desc"]];
			options.sAjaxSource = global.context+"/web/job/searchbycon";
			options.functionList = {"checkTr":checkTr,"operate":operate,"jobStatus":jobStatus};
			jobTable = datatables.init(options);
			var result = util.getSearchData("#search-area") ;
			jobTable.setParams(result);
			$('#jobTable').css('width', "100%");
			return jobTable.create();
		};
		
		var jobForm = $('#jobForm').validate({
			onkeyup : false,
			rules:{
				jobName:{
					required: true,
		    		rangelength: [2,11],
		    	},
		    	jobGroup:{
		    		required: true,
	            	rangelength: [2,30],
	            },
	            cronExpression:{
	            	required: true,
	            	rangelength: [2,50],
	            },
	            description:{
	            	required: true,
	            	rangelength: [0,100],
	            }
		    },
		    messages : {
		    	jobName : {
		    		rangelength : $.format("姓名长度：{2}-{11}个字符"),
		    	},
		    	jobGroup:{
	        	   rangelength : $.format("姓名长度：{2}-{30}个字符"),
	           },
	           cronExpression:{
	        	   rangelength : $.format("姓名长度：{2}-{50}个字符"),
			   },
			   description:{
				   rangelength : $.format("姓名长度：{0}-{100}个字符"),
			   }
		    },
			submitHandler: function(form) {
				if($("#beanClass").val().trim()!=""&&$("#springId").val().trim()!=""){
					$('#alertsInfo').find(".modal-body").text(
					"任务对应处理类(普通class)和任务对应处理类(springBean)只能选择一个");
			        $('#alertsInfo').modal();
			        return;
				}
				$('#addOrupdateBtn').attr('disabled',"true");
				util.ajax_submit(form).complete(function(xhr) {
					var result = $.parseJSON(xhr.responseText);
					if(result.code=="ACK"){
						jobTable.invoke("fnDraw");//refresh表格
					}
					$("#jobModal").hide();
					$("#jobModal input[type='text']").val('');
					$("#jobForm input").each(function(){
						$(this).val("");
					});
				});
		    },
		    errorPlacement:function(error, element){//自定义错误提示放置的位置
		    	var $errorPanel = '<div class="teacher-error-panel"></div>';
		    	element.closest(".info_item").after($errorPanel);
		    	error.appendTo(element.closest(".info_item").next('.teacher-error-panel'));
		    },
		    highlight: function(element, errorClass) {  
		    	$(element).addClass('highlight-error');//未通过验证的元素高亮
	        },
	        unhighlight: function(element, errorClass) {  
		    	$(element).removeClass('highlight-error');//通过验证去掉高亮
	        },
	        success: function(label) {  
	        }  
		});
		
		var init = function(){
			_jobTable();
			bindEvent();
		};
		
		var bindEvent = function(){
			$("body").on('click','.changeJobStatus',function(){
				var target = $(this);
				var xx = target.data('id').split(",");
				var cmd;
				if(xx[1]=='0'){//表示点击的是开始按钮
					cmd = "start";
				}else{
					cmd = "stop";
				}
				$.ajax({
					'url' : global.context + '/web/job/changeJobStatus',
					'data' : 'jobId='+ xx[0]+'&cmd='+cmd,
					'type' : 'POST',
					'dataType' : 'json',
					'success' : function(result) {
						if (result.code == 'ACK') {
							jobTable.invoke("fnDraw");// 删除成功后，refresh列表
						}
					},
					'error' : function() {
					}
				});
			});
			$("body").on('click','.PauseJob',function(){
				var target = $(this);
				var now = $(this).text();
				var url = "";
				if(now=="暂停"){
					url = "pausejob";
				}else if(now=="恢复"){
					url = "resumejob";
				}
				$.ajax({
					'url' : global.context + '/web/job/'+url,
					'data' : 'jobId='+ target.data('id'),
					'type' : 'POST',
					'dataType' : 'json',
					'success' : function(result) {
						if (result.code == 'ACK') {//不用刷新表格
							$(".PauseJob").each(function(){
								if($(this).data('id')==target.data('id')){
									if(now=="暂停"){
										$(this).text("恢复");
									}else if(now=="恢复"){
										$(this).text("暂停");
									}
								}
							});
							jobTable.invoke("fnDraw");// 删除成功后，refresh列表
						}
					},
					'error' : function() {
					}
				});
			});
			$("body").on('click','.ExeJob',function(){
				var target = $(this);
				$.ajax({
					'url' : global.context + '/web/job/immediateExejob',
					'data' : 'jobId='+ target.data('id'),
					'type' : 'POST',
					'dataType' : 'json',
					'success' : function(result) {
						if (result.code == 'ACK') {//不用刷新表格
							
						}
					},
					'error' : function() {
					}
				});
			});
			
			$("body").on('click','.editJob',function(){
				$('#addOrupdateBtn').removeAttr('disabled');
				var target = $(this);
				$("#jobModal").show();
				$.ajax({
					'url' : global.context + '/web/job/toedit',
					'data' : 'jobId='+ target.data('id'),
					'type' : 'POST',
					'dataType' : 'json',
					'success' : function(result) {
						$("#jobId").val(result.id);
						$("#jobName").val(result.jobName);
						$("#jobGroup").val(result.jobGroup);
						$("#cronExpression").val(result.cronExpression);
						$("#description").val(result.description);
						$("#beanClass").val(result.beanClass);
						$("#methodName").val(result.methodName);
						$("#springId").val(result.springId);
					},
					'error' : function() {
					}
				});
				
			});
			$("body").on('click','.close',function(){
				$("#jobModal").hide();
				$("#jobForm input").each(function(){
					$(this).val("");
				});
			});
			$("body").on('click','#addJob',function(){
				$('#addOrupdateBtn').removeAttr('disabled');
				$("#jobModal").show();
				$("#jobForm input").each(function(){
					$(this).val("");
				});
				$("#jobForm").attr('action',global.context +"/web/job/add");
			});
			$("body").on('click','#search-btn',function(){
				var result = util.getSearchData("#search-area") ;
				jobTable.setParams(result);
				jobTable.invoke("fnDraw");
			});
			$("body").on('click','.deleteJob',function(){
				var target = $(this);
				bootbox.confirm({
					buttons: {  
			            confirm: {  
			                label: '确认',  
			                className: 'btn-myStyle'  
			            },  
			            cancel: {  
			                label: '取消',  
			                className: 'btn-default'  
			            }  
		      		 },  
					message: "确认要删除吗?",
					callback: function(isOk) {
						if(isOk){
							$.ajax({
						        'url' : global.context+'/web/job/deleteone',
						        'data':'id='+target.data('id'),
						        'type' : 'POST',
						        'dataType' : 'json',
						        'success' : function(result) {
						        	if(result.code=='ACK'){
						        		jobTable.invoke("fnDraw");// 删除成功后，refresh列表
						        	}
						        },
						        'error' : function() {
						        }
							});
						}
					},
					className: "bootbox-sms"
				});	
			});
			$("#delete-btn").click(function(){
				var ids=new Array();
				var checkedCount=0;
				 $("input[name='subBox']:checked").each(function(){
					 ids[checkedCount]=$(this).attr('value');
					 checkedCount++;
				 });
				 if(checkedCount==0){
					 $('#alertsWarning').find(".modal-body").text("请选择对象！");
					 $('#alertsWarning').modal();
					 return;
				 }
				 bootbox.confirm({
						buttons: {  
				            confirm: {  
				                label: '确认',  
				                className: 'btn-myStyle'  
				            },  
				            cancel: {  
				                label: '取消',  
				                className: 'btn-default'  
				            }  
			      		 },  
						message: "确认要删除吗?",
						callback: function(isOk) {
							if(isOk){
								$.ajax({
									type: "POST",
								     url: global.context +"/web/job/deleteids",
								     data:{'ids':ids.toString()},
								     dataType:"json",
								     async: false,   
							        'success' : function(data) {
							        	if(data.code=='ACK'){
							        		jobTable.invoke("fnDraw");// 删除成功后，refresh列表
							        	}
							        },
							        'error' : function() {
							        }
								});
							}
						},
						className: "bootbox-sms"
				});
			});
		};
		
		init();
		
		// 全选
		$("#checkAll").click(function() {
			if (this.checked) {
				$("input[name='subBox']").each(function() {
					this.checked = true;
				});
			} else {
				$("input[name='subBox']").each(function() {
					this.checked = false;
				});
			}
		});
});